package com.example.servlet;

import com.example.dao.NovelDao;
import com.example.dao.UserDao;
import com.example.domain.Novel;
import com.example.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
@WebServlet("/AdminUserAddServlet")
public class AdminUserAddServlet extends HttpServlet{
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        doPost(request,response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        request.setCharacterEncoding("utf-8");
        UserDao userDao = new UserDao();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String isAdmin = request.getParameter("isAdmin");
        boolean flag = userDao.checkUsername(username);
        int affectedRow = 0;

        if (flag){
            request.setAttribute("msg","用户名已存在,添加失败！");
            request.getRequestDispatcher("admin/admin_UserAdd.jsp").forward(request,response);
            return;
        }
        if(userDao.checkEmail(email)){
            request.setAttribute("msg","邮箱已存在,添加失败！");
            request.getRequestDispatcher("admin/admin_UserAdd.jsp").forward(request,response);
            return;
        }else{
            if(isAdmin.equals("true")){
                affectedRow = userDao.adminAddUser(new User(username,password,email,true));
            }else {
                affectedRow = userDao.adminAddUser(new User(username,password,email,false));
            }
            if(affectedRow==0){
                request.setAttribute("msg","添加失败！！");
                request.getRequestDispatcher("admin_UserAdd.jsp").forward(request,response);
            }
            request.setAttribute("msg","添加成功！！");
            request.getRequestDispatcher("admin_UserAdd.jsp").forward(request,response);
        }
    }
}
